<template>
    <div>
        <el-card shadow="never">
            <el-page-header @back="goBack" content="库存详情" />

            <el-descriptions title="店铺信息" :column="3" border style="margin-top: 16px;">
                <el-descriptions-item label="店铺ID">{{ detail.id }}</el-descriptions-item>
                <el-descriptions-item label="店铺名">{{ detail.name }}</el-descriptions-item>
                <el-descriptions-item label="现金余额">{{ formatPrice(detail.capitalBalance) }}</el-descriptions-item>
            </el-descriptions>

            <el-card shadow="never" style="margin-top: 16px;">
                <template slot="header">
                    <span>店铺物料列表</span>
                    <el-button type="primary" size="mini" @click="handleAddMaterial"
                        style="float: right;">添加物料</el-button>
                </template>
                <el-table :data="detail.materialInfoList || []" border fit>
                    <el-table-column label="店铺ID" prop="dpId" align="center" />
                    <el-table-column label="物料名称" prop="materialName" align="center" />
                    <el-table-column label="物料类型" prop="materialType" align="center" />
                    <el-table-column label="重量" prop="weight" align="center" >
                        <template slot-scope="scope">
                            {{ formatWeight(scope.row.weight) }}g
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>
        </el-card>

        <!-- 添加物料对话框 -->
        <MaterialAddDialog :visible.sync="materialDialogVisible" :store-id="detail.id" @submit="handleMaterialSubmit"
            @close="handleMaterialDialogClose" />

        <!-- 流水列表 -->
        <el-card shadow="never" style="margin-top: 16px;">
            <template slot="header">
                <span>流水列表</span>
            </template>

            <!-- 查询表单 -->
            <el-form :model="tradeQueryForm" :inline="true" class="trade-query-form">
                <el-form-item label="物料名称">
                    <el-input v-model="tradeQueryForm.materialName" placeholder="请输入物料名称" clearable
                        style="width: 200px;" />
                </el-form-item>
                <el-form-item label="物料类型">
                    <el-select v-model="tradeQueryForm.materialType" placeholder="请选择物料类型" clearable
                        style="width: 150px;">
                        <el-option v-for="item in materialTypes" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="交易类型">
                    <el-select v-model="tradeQueryForm.tradeType" placeholder="请选择交易类型" clearable style="width: 150px;">
                        <el-option v-for="item in tradeTypes" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="交易时间">
                    <el-date-picker v-model="tradeTimeRange" type="datetimerange" range-separator="至"
                        start-placeholder="开始时间" end-placeholder="结束时间" format="yyyy-MM-dd HH:mm:ss"
                        value-format="yyyy-MM-dd HH:mm:ss" style="width: 350px;" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleTradeQuery">查询</el-button>
                    <el-button @click="handleTradeReset">重置</el-button>
                </el-form-item>
            </el-form>

            <!-- 流水数据表格 -->
            <el-table :data="tradeList" border fit v-loading="tradeLoading" style="margin-top: 16px;">
                <el-table-column label="店铺名称" prop="dpName" align="center" width="120" />
                <el-table-column label="物料类型" prop="materialType" align="center" width="120">
                    <template slot-scope="scope">
                        <el-tag :color="getMaterialTypeColor(scope.row.materialType)">
                            {{ getMaterialTypeLabel(scope.row.materialType) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="交易类型" prop="tradeType" align="center" width="120">
                    <template slot-scope="scope">
                        <el-tag :color="getTradeTypeColor(scope.row.tradeType)" style="color: white;">
                            {{ getTradeTypeLabel(scope.row.tradeType) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="交易时间" prop="tradeTime" align="center" width="180" />
                <el-table-column label="重量" prop="weight" align="center" width="100" >
                    <template slot-scope="scope">
                        {{ formatWeight(scope.row.weight) }}g
                    </template>
                </el-table-column>

                <el-table-column label="备注" prop="remarks" align="center" min-width="200" />
            </el-table>

            <!-- 分页 -->
            <el-pagination @size-change="handleTradeSizeChange" @current-change="handleTradeCurrentChange"
                :current-page="tradeQueryForm.current" :page-sizes="[10, 20, 50, 100]" :page-size="tradeQueryForm.size"
                layout="total, sizes, prev, pager, next, jumper" :total="tradeTotal"
                style="margin-top: 16px; text-align: right;" />
        </el-card>
    </div>
</template>

<script>
import { inventoryDetail } from './api/inventory'
import { addMaterial, getLogList } from './api/material'
import MaterialAddDialog from './MaterialAddDialog.vue'
import {
    MATERIAL_TYPES,
    TRADE_TYPES,
    getMaterialTypeLabel,
    getTradeTypeLabel,
    getMaterialTypeColor
} from './options/materialType'

export default {
    name: 'InventoryDetail',
    components: {
        MaterialAddDialog
    },
    data() {
        return {
            id: '',
            loading: false,
            detail: {},
            materialDialogVisible: false,

            // 流水列表相关
            tradeList: [],
            tradeTotal: 0,
            tradeLoading: false,
            tradeTimeRange: [],
            tradeQueryForm: {
                size: 20,
                current: 1,
                dpId: '',
                materialName: '',
                materialType: '',
                tradeType: null,
                startTradeTime: '',
                endTradeTime: ''
            },
            materialTypes: MATERIAL_TYPES,
            tradeTypes: TRADE_TYPES
        }
    },
    created() {
        console.log(120, this.$route.query)

        this.id = this.$route.query.id
        this.getDetail()

    },
    methods: {
        // 格式化价格
        formatPrice(price) {
            if (price === null || price === undefined || price === '') return '0.00'
            const num = Number(price)
            if (!isFinite(num)) return '0.00'
            return num.toLocaleString('zh-CN', {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
            })
        },
        // 重量 千分符
        formatWeight(weight) {
            if (weight === null || weight === undefined || weight === '') return '0'
            const num = Number(weight)
            if (!isFinite(num)) return '0'
            return num.toLocaleString('zh-CN')
        },
        goBack() {
            this.$router.push({ path: '/inventory/list' })
        },
        async getDetail() {
            if (!this.id) return
            this.loading = true
            try {
                const res = await inventoryDetail(this.id)
                this.detail = Array.isArray(res) ? (res[0] || {}) : (res.data || res || {})
                // 设置店铺ID到查询表单
                this.tradeQueryForm.dpId = this.detail.id
                this.getTradeList()
            } finally {
                this.loading = false
            }
        },
        handleAddMaterial() {
            this.materialDialogVisible = true
        },

        async handleMaterialSubmit(formData) {
            try {
                this.loading = true
                await addMaterial(formData)
                this.$message.success('物料添加成功')
                this.getDetail()
            } catch (error) {
                console.error('添加物料失败:', error)
            } finally {
                this.loading = false
            }
        },

        handleMaterialDialogClose() {
            this.materialDialogVisible = false
        },

        // 流水列表相关方法
        async getTradeList() {
            if (!this.tradeQueryForm.dpId) return

            this.tradeLoading = true
            try {
                const res = await getLogList(this.tradeQueryForm)
                this.tradeList = res.data?.records || res.records || []
                this.tradeTotal = res.data?.total || res.total || 0
            } catch (error) {
                console.error('获取流水列表失败:', error)
            } finally {
                this.tradeLoading = false
            }
        },

        handleTradeQuery() {
            // 处理时间范围
            if (this.tradeTimeRange && this.tradeTimeRange.length === 2) {
                this.tradeQueryForm.startTradeTime = this.tradeTimeRange[0]
                this.tradeQueryForm.endTradeTime = this.tradeTimeRange[1]
            } else {
                this.tradeQueryForm.startTradeTime = ''
                this.tradeQueryForm.endTradeTime = ''
            }

            this.tradeQueryForm.current = 1
            this.getTradeList()
        },

        handleTradeReset() {
            this.tradeQueryForm = {
                size: 20,
                current: 1,
                dpId: this.detail.id,
                materialName: '',
                materialType: '',
                tradeType: null,
                startTradeTime: '',
                endTradeTime: ''
            }
            this.tradeTimeRange = []
            this.getTradeList()
        },

        handleTradeSizeChange(size) {
            this.tradeQueryForm.size = size
            this.tradeQueryForm.current = 1
            this.getTradeList()
        },

        handleTradeCurrentChange(current) {
            this.tradeQueryForm.current = current
            this.getTradeList()
        },

        // 工具方法
        getMaterialTypeLabel,
        getTradeTypeLabel,
        getMaterialTypeColor,

        getTradeTypeColor(value) {
            const type = this.tradeTypes.find((item) => item.value === value)
            return type ? type.color : '#808080'
        }
    }
}
</script>

<style lang="scss" scoped>
.trade-query-form {
    margin-bottom: 16px;

    .el-form-item {
        margin-bottom: 16px;
    }
}
</style>
